﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：KernelModule.cs
// 功能描述：TongTongMall
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using Castle.MicroKernel.Registration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.Commanding.Messaging;
using TongTongMall.Configuration;
using TongTongMall.Dependecy;
using TongTongMall.Domain.Uow;
using TongTongMall.Events;
using TongTongMall.Modules;
using TongTongMall.Runtime.Session;
using TongTongMall.Tenant;

namespace TongTongMall
{
    public class KernelModule : BaseModule
    {
        public override void PreInitialize()
        {
            IocManager.AddConventionalRegistrar(new TongTongMallConventionalRegistrar());
            UnitOfWorkRegistrar.Initialize(IocManager);
        }

        public override void PostInitialize()
        {
            RegisterMissingComponents();

            IocManager.Resolve<SettingDefinitionManager>().Initialize();
        }

        public override void Initialize()
        {
            IocManager.IocContainer.Install(new EventBusInstaller(IocManager));
            //扫描tongtongmall模块内的依赖注入关系，但不进行全局的自动注册行为
            IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly(),
               new ConventionalRegistrationConfig
               {
                   InstallInstallers = false
               });
        }

        private void RegisterMissingComponents()
        {
            IocManager.RegisterIfNot<IUnitOfWork, NullUnitOfWork>(DependencyLifeStyle.Transient);
            IocManager.RegisterIfNot<ITongTongMallSession, TongTongMallSession>(DependencyLifeStyle.Singleton);
            IocManager.RegisterIfNot<IEventConsumer, EventConsumer>(DependencyLifeStyle.Singleton);
        }

        /// <summary>
        /// 配置项在不同作用域下对应缓存的有效日期
        /// </summary>
        private void ConfigureCaches()
        {
            Configuration.Caching.Configure(TenantCacheName.ApplicationSettings, cache =>
            {
                cache.DefaultSlidingExpireTime = TimeSpan.FromDays(30);
            });

            Configuration.Caching.Configure(TenantCacheName.TenantSettings, cache =>
            {
                cache.DefaultSlidingExpireTime = TimeSpan.FromDays(30);
            });

            Configuration.Caching.Configure(TenantCacheName.UserSettings, cache =>
            {
                cache.DefaultSlidingExpireTime = TimeSpan.FromMinutes(20);
            });
        }
    }
}
